/*
 * 用户注册界面
 */
package com.wonyesoft.wuliu.acticity;

import httptools.HttpJsonTool;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javabeen.UserInfoBeen;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

import tools.SD_Finder;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;


import cn.jpush.android.api.JPushInterface;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.wonyesoft.wuliu.AppContent;
import com.wonyesoft.wuliu.R;
import com.wonyesoft.wuliu.acticity.base.BaseActivity;
import com.wonyesoft.wuliu.acticity.order.AddCargoOrderActivity;
import com.wonyesoft.wuliu.acticity.user.RestPassWordActivity;
import com.wonyesoft.wuliu.acticity.utils.StringUtils;
import com.wonyesoft.wuliu.acticity.utils.ToastUtils;
import com.wonyesoft.wuliu.api.GagApi;
import com.wonyesoft.wuliu.vo.JsonRequest;
import com.wonyesoft.wuliu.vo.JsonResponse;
import com.wonyesoft.wuliu.vo.State;

public class UserLoginActivity extends BaseActivity implements OnClickListener {

	private TabHost mTabHost;
	private RadioGroup mRadioGroup;
	private TextView title, head_right,login_zhuchetext;
//	private ImageView head_left;
	private PreferencesCookieStore preferencesCookieStore;
	private SharedPreferences share;
	private String key = "UserInfo";
	private String name, password;
	private HttpUtils http;
	private String token;
	private EditText login_id, login_pwd;
	public static Gson gson = new Gson();
	private RequestParams params;
	private Editor editor;
	private Button login_denglu;
	private List<UserInfoBeen> userInfoBeens;
	private AppContent app;
	@SuppressLint("NewApi")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		// System.out.println("regsiter");
		preferencesCookieStore = new PreferencesCookieStore(this);
		http = new HttpUtils();
		Start_PushMessage();
		title = (TextView) findViewById(R.id.head_title);
		//head_left = (ImageView) findViewById(R.id.head_left);
		head_right = (TextView) findViewById(R.id.head_right);
		login_id = (EditText) findViewById(R.id.login_id);
		login_pwd = (EditText) findViewById(R.id.login_pwd);
		login_denglu = (Button) findViewById(R.id.login_denglu);
		login_zhuchetext = (TextView) findViewById(R.id.login_zhuchetext);
		//head_left.setVisibility(0);
		title.setText("用户登录");
		head_right.setVisibility(0);
		head_right.setOnClickListener(this);
		head_right.setTextSize(12);
		head_right.setText("忘记密码");
		//head_left.setOnClickListener(this);
		login_denglu.setOnClickListener(this);
		login_zhuchetext.setOnClickListener(this);
		app=(AppContent) getApplication();
		share = this.getSharedPreferences(key, Context.MODE_PRIVATE);
		//initSharePreferences();
		MakeFolder();
	}

	private void autoLogin() {
		editor = share.edit();
		name=share.getString("userPhone", null);
		password=share.getString("userPassword", null);
		if (name==null) {
			return;
		}
		if (password==null) {
			return;
		}
		login(true);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.head_left:
			finish();
			break;
		case R.id.head_right:
			openActivity(RestPassWordActivity.class);
			break;
		case R.id.login_denglu:
			// showAlertDialog("注册中", "正在注册。。。。");
			login(false);
			break;
		case R.id.login_zhuchetext:
			openActivity(UserRegisterActivity.class);
//			finish();
		default:
			break;
		}
	}

	private void login(boolean flag) {
		if (!flag) {
			name = login_id.getText().toString();
			password = login_pwd.getText().toString();
		}
		showLoadingDialog("登录中");
		
		// 判断输入
		if (StringUtils.isEmpty(name)) {
			showLongToast("请输入用户名");
			dismissLoadingDialog();
			return;
		}
		if (StringUtils.isEmpty(password)) {
			showLongToast("请输入密码");
			dismissLoadingDialog();
			return;
		}
		
		Map<String, Object> dataMap = new HashMap<String, Object>();
	
		dataMap.put("userPhone", name);
		dataMap.put("userPassword", password);
		HttpJsonTool httpJsonTool=new HttpJsonTool(this,true);
		httpJsonTool.SetOnLister(new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				
				if (msg.what==1) {
					dismissLoadingDialog();
				//	Toast.makeText(UserLoginActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
					userInfoBeens=(List<UserInfoBeen>) msg.obj;
					if (userInfoBeens.size()>0) {
					
						app.userId = userInfoBeens.get(0).getCargoownerid()+"";
						Log.v("app.userId", app.userId);
						app.userinfobeen = userInfoBeens.get(0);
						SeaveUserInfo();
					}else {
						Toast.makeText(UserLoginActivity.this, "请检查网络连接状态...", Toast.LENGTH_LONG).show();
						dismissLoadingDialog();
					}
				}else {
					dismissLoadingDialog();
					Toast.makeText(UserLoginActivity.this, "用户名或者密码错误", Toast.LENGTH_LONG).show();
				}
			}
		});
		//http://192.168.1.122:8080/cqtczh/shipper/registerForMobile.do loginFormobile
		//http://192.168.1.122:8080/cqtczh/shipper/loginFormobile.do
		Type type=new TypeToken<List<UserInfoBeen>>(){}.getType();
		httpJsonTool.StartWork(dataMap, GagApi.LOGIN, type, null);
	}

	
	
	public void Start_PushMessage() {
		JPushInterface.resumePush(getApplicationContext());
//		PushManager.startWork(getApplicationContext(),
//				PushConstants.LOGIN_TYPE_API_KEY, "Gv9FASP1Ob4KLLPNC0iotuVg");
		// Log.d("请输入", "信息");
		/*
		 * 参数 layoutId ：自定义layout资源id layoutIconId ：自定义layout中显示icon 的id
		 * layoutTitleId ：自定义layout中显示标题的id layoutTextId ：自定义layout中显示内容的id
		 */
//
//		int layoutId = R.layout.notification_custom_builder;
//		int layoutIconId = R.id.notification_icon;
//		int layoutTitleId = R.id.notification_title;
//		int layoutTextId = R.id.notification_text;
//		CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
//				getApplicationContext(), layoutId, layoutIconId, layoutTitleId,
//				layoutTextId);
//		cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
//		cBuilder.setNotificationDefaults(Notification.DEFAULT_SOUND
//				| Notification.DEFAULT_VIBRATE);
//		cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
//		cBuilder.setLayoutDrawable(R.drawable.ic_launcher);
//		PushManager.setNotificationBuilder(this, 1, cBuilder);
	}

	public void MakeFolder(){
		String root=SD_Finder.GetPaht();
		if (root!=null) {
			//File.separator
		
		File file = new File(root+GagApi.TCZH_File);
		File TMP = new File(root+GagApi.IMAGE_FILE_PATH);
		File sound=new File(root+GagApi.SOUND_FILE_PATH);
		File file_apk=new File(root+GagApi.FILE_PATH);
		File UploadFile=new File(root+GagApi.UP_LOAD_FILE);
		// msg.obj=mBitmap;
		if (!file.exists()) {
			file.mkdir();
		//	 Log.v("下载", "创建图片路径："+file.getPath());
		}
		if (!TMP.exists()) {
			TMP.mkdir();
		//	 Log.v("下载",
	//		 "创建图片路径："+TMP.getPath());
		}
		if (!sound.exists()) {
			sound.mkdir();
		//	 Log.v("下载",
		//			 "创建图片路径："+sound.getPath());
		}
		if (!file_apk.exists()) {
			file_apk.mkdir();
		}
		if (!UploadFile.exists()) {
			try {
				
				UploadFile.createNewFile();
				Log.v("创建文件-->", UploadFile.getPath());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		}
		autoLogin();
	}
	
	
	// 保存用户密码和id
		private void SeaveUserInfo() {
			
			editor = share.edit();
			editor.putString("userPhone",name);
			editor.putString("userPassword",password);
			editor.commit();
		//	AddCargoActivity();
			dismissLoadingDialog();
			Intent intent=new Intent(this,TestAcivity.class);
		//	Intent intent=new Intent(this,MainActivityActivity.class);
			UserLoginActivity.this.finish();
			startActivity(intent);
		}
	
		@Override
		protected void onResume() {
			// TODO Auto-generated method stub
			
			JPushInterface.onResume(this);
			super.onResume();
		}
		
		@Override
		protected void onPause() {
			// TODO Auto-generated method stub
			
			JPushInterface.onPause(this);
			super.onPause();
		}
}
